﻿#include <DCTft/DCFrame.h>
#include "bsp/bsp_crc.h"
#include "bsp/bsp_converter.h"

#define BYTE_ORDER       true


//组包 包 -> 数组
void DCFrame::make_pack(uint8_t* buff, uint16_t* len)
{
    uint16_t index = 0;
    uint16_t crc = 0x1122;
    buff[index++] = 0xEE;
    buff[index++] = 0xB5;
    memcpy(buff + index, this->paload, this->paload_len);
    index += this->paload_len;

#if DC_COMM_CRC == 1
    crc = bsp_crc16(buff + 1, index - 1);
    bsp_cnv_uint16_to_arr(buff + index, crc, BYTE_ORDER);
    index += 2;
#endif

    buff[index++] = end[0];
    buff[index++] = end[1];
    buff[index++] = end[2];
    buff[index++] = end[3];
    *len = index;
}

//解包 数组 -> 包
void DCFrame::unmake_pack(uint8_t* buff, uint16_t* len)
{
    uint16_t index = 0;

    this->head = buff[index++];

    this->paload_len = *len - 5;
    this->paload = &buff[1];
    index += paload_len;

#if DC_COMM_CRC == 1
    this.crc = bsp_cnv_arr_to_uint16(buff+index, BYTE_ORDER);
    index += 2;
#endif

    this->end[0] = buff[index++];
    this->end[1] = buff[index++];
    this->end[2] = buff[index++];
    this->end[3] = buff[index++];
}


bool DCFrameRecv::proc_one_byte(DCFrame* frame,uint8_t data)
{
    if (recv_len == 0)
    {
        recv_buff[0] = recv_buff[1];
        recv_buff[1] = data;

        if ((recv_buff[0] == 0xee)&&(recv_buff[1]==0xb1))
        {
            recv_len = 2;
            recv_index = 2;
        }
    }
    else
    {
        recv_buff[recv_index++] = data;
        recv_len = recv_index;

        if(recv_len >= 1024)
            recv_len = 0;

#if DC_COMM_CRC == 0
        if(recv_index > 6 &&
#else
        if(recv_index > 6 + 2 &&
#endif
           recv_buff[recv_index - 4] == 0xff &&
           recv_buff[recv_index - 3] == 0xfc &&
           recv_buff[recv_index - 2] == 0xff &&
           recv_buff[recv_index - 1] == 0xff)
        {

#if DC_COMM_CRC == 1
            uint16_t crc = bsp_crc16(&recv_buff[1], recv_index - 7);
            uint16_t pack_crc = bsp_cnv_arr_to_uint16(&recv_buff[recv_index - 6], BYTE_ORDER);
            if (pack_crc == crc)//crc校验
            {
                frame->unmake_pack(recv_buff, &recv_len); //解包
                recv_index = 0;
                recv_len = 0;
                return true;
            }
            else
            {
                recv_index = 0;
                recv_len = 0;
                return false;
            }
#else
            frame->unmake_pack(recv_buff, &recv_len); //解包
            recv_index = 0;
            recv_len = 0;
            return true;
#endif
        }
    }
    return false;
}


